﻿using Cysharp.Threading.Tasks;
using HBFramework;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class SSceneManager : Singleton<SSceneManager>, ISingleton
{
    private Dictionary<string, BaseSceneController> sceneDict;
    private BaseSceneController activeScene;
    private BaseSceneController lastScene;

    public void OnInit()
    {
        sceneDict = new Dictionary<string, BaseSceneController>();
    }

    public void OnDestroy()
    {

    }

    /// <summary>
    /// 加载场景
    /// </summary>
    /// <param name="sceneController"></param>
    /// <param name="sceneName"></param>
    /// <param name="active"></param>
    /// <returns></returns>
    public async UniTask LoadScene(BaseSceneController sceneController, string sceneName, bool active = false)
    {
        var scene = await AssetManagerProxy.Instance.LoadScene(sceneName, LoadSceneMode.Additive);
        sceneController.BindScene(scene);
        sceneDict.Add(sceneName, sceneController);
        if (active)
            ActiveScene(sceneName);
        else
            sceneController.OnDisable();
    }

    /// <summary>
    /// 释放场景
    /// </summary>
    /// <param name="sceneController"></param>
    /// <returns></returns>
    public async UniTask ReleaseScene(string sceneName)
    {
        var sceneController = GetScene(sceneName);
        if (sceneController == null)
            return;
        sceneDict.Remove(sceneName);
        await SceneManager.UnloadSceneAsync(sceneController.Scene);
        sceneController.OnRelease();
    }

    /// <summary>
    /// 激活场景
    /// </summary>
    /// <param name="sceneController"></param>
    public void ActiveScene(string sceneName)
    {
        var sceneController = GetScene(sceneName);
        if (sceneController == null)
            return;
        ActiveScene(sceneController);
    }

    /// <summary>
    /// 激活场景
    /// </summary>
    /// <param name="sceneController"></param>
    public void ActiveScene(BaseSceneController sceneController)
    {
        if (activeScene != null)
        {
            lastScene = activeScene;
            activeScene?.OnDisable();
        }
        sceneController.OnEnable();
        activeScene = sceneController;
    }

    /// <summary>
    /// 激活上一个场景
    /// </summary>
    public void ActiveLastScene()
    {
        if (lastScene == null)
        {
            return;
        }
        ActiveScene(lastScene);
    }

    /// <summary>
    /// 获取场景
    /// </summary>
    /// <param name="sceneName"></param>
    public BaseSceneController GetScene(string sceneName)
    {
        if (sceneDict.ContainsKey(sceneName))
        {
            return sceneDict[sceneName];
        }
        return null;
    }
}
